package com.example.gpstest.activity;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bin.david.form.core.SmartTable;
import com.example.gpstest.DataBean.DataIntervalBean;
import com.example.gpstest.DataBean.DataSearchStarBean;
import com.example.gpstest.DataBean.DataTestBean;
import com.example.gpstest.R;
import com.example.gpstest.Utils.ExcelUtil;
import com.example.gpstest.Utils.GPSConst;
import com.example.gpstest.Utils.KmlUtils;
import com.example.gpstest.Utils.LocationUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnInputConfirmListener;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class GPSStarInterval extends AppCompatActivity {
    private LocationManager locationManagerInterval;
    private EditText et_Number,et_Times,et_Minsnr,et_Maxsnr;
    private Button btnStart,btnStop,btnDeriveInterval;
    private TextView tv_Content;
    private SmartTable smartTable;
    private static float STAR_MAX_SNR = 0;//搜星最大有效snr 上限
    private static float STAR_MIN_SNR = 0;//最低有效snr 下限
    private static Integer NUMBER = 1;//搜星次数
    private static long TIMES = 5;//最低时间
    int countnumber = 0;
    private List<DataIntervalBean> dataIntervalBean = new ArrayList<>();
    private List<DataIntervalBean> dataIntervalBean1 = new ArrayList<>();
    boolean bStar=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gps_star_interval);
        if (locationManagerInterval == null) {
            locationManagerInterval = (LocationManager) getSystemService(LOCATION_SERVICE);
        }
        et_Times=findViewById(R.id.et_times);
        et_Number=findViewById(R.id.et_number);
        et_Minsnr=findViewById(R.id.et_minsnr);
        et_Maxsnr=findViewById(R.id.et_maxsnr);
        btnStart=findViewById(R.id.btn_start);
        btnStop=findViewById(R.id.btn_stop);
        btnDeriveInterval=findViewById(R.id.btn_derive_interval);
        tv_Content=findViewById(R.id.tv_content);
        smartTable=findViewById(R.id.smartTableInterval);
        String etMaxsnrStr = et_Maxsnr.getText().toString();
        String etMinsnrStr = et_Minsnr.getText().toString();
        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_Content.setText("开始测试");
                countnumber=0;
                dataIntervalBean1.clear();
                String etMaxsnrStr = et_Maxsnr.getText().toString();
                String etMinsnrStr = et_Minsnr.getText().toString();
                String etNumber = et_Number.getText().toString();
                String etTimes = et_Times.getText().toString();
                if (etMaxsnrStr.isEmpty()){
                    ExcelUtil.ShortToast(GPSStarInterval.this,"输入区间值");
                    return;
                }
                if (etMinsnrStr.isEmpty()){
                    ExcelUtil.ShortToast(GPSStarInterval.this,"输入区间值");
                    return;
                }
                if (etNumber.isEmpty()){
                    ExcelUtil.ShortToast(GPSStarInterval.this,"输入次数");
                    return;
                }
                if (etTimes.isEmpty()){
                    ExcelUtil.ShortToast(GPSStarInterval.this,"输入时间");
                    return;
                }
                STAR_MAX_SNR=Float.valueOf(etMaxsnrStr);
                STAR_MIN_SNR=Float.valueOf(etMinsnrStr);
                NUMBER=Integer.valueOf(etNumber);
                TIMES=Long.valueOf(etTimes)*1000;
                btnStart.setEnabled(false);
                startLocation();
                handler.postDelayed(runnable,TIMES);
            }
        });
        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnStart.setEnabled(true);
                stopGPSListener();
                handler.removeCallbacks(runnable);
            }
        });
        btnDeriveInterval.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new XPopup.Builder(GPSStarInterval.this)
                        .asInputConfirm("保存", "默认保存的路径地址:/storage/emulated/0/GPSTestFile/","Interval.xls",null,
                                new OnInputConfirmListener() {
                                    @Override
                                    public void onConfirm(String text) {
                                        if (text.contains(".xls")){
                                            getExcelInterval(text);
                                        }else {
                                            ExcelUtil.ShortToast(GPSStarInterval.this,"保存失败，不是xls文件格式");
                                        }
                                    }
                                })
                        .show();
            }
        });
    }



    @SuppressLint("MissingPermission")
    private void startLocation() {
        //判断GPS是否正常启动
        if (!locationManagerInterval.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Toast.makeText(this, "请开启GPS导航", Toast.LENGTH_SHORT).show();
            //返回开启GPS导航设置界面
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(intent, 0);
            return;
        }
        //1000位最小的时间间隔，1为最小位移变化；也就是说每隔5000ms会回调一次位置信息
        locationManagerInterval.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
        //添加卫星状态改变监听
        locationManagerInterval.addGpsStatusListener(gpsStatusListener);
    }

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            countnumber++;
            if (countnumber<=NUMBER) {
                tv_Content.setText("开始测试  "+countnumber+"/"+NUMBER);
                bStar = true;
                handler.postDelayed(runnable, TIMES);
            }
        }
    };
    LocationListener locationListener = new LocationListener() {
        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        public void onLocationChanged(Location location) {

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };
    private GpsStatus.Listener gpsStatusListener = new GpsStatus.Listener() {
        @Override
        public void onGpsStatusChanged(int event) {
            switch (event) {
                //卫星状态改变
                case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                    dataIntervalBean.clear();
                    //获取当前状态
                    @SuppressLint("MissingPermission") GpsStatus gpsStatus = locationManagerInterval.getGpsStatus(null);
                    //获取卫星颗数的默认最大值
                    int maxSatellites = gpsStatus.getMaxSatellites();
                    //获取所有的卫星
                    Iterator<GpsSatellite> iters = gpsStatus.getSatellites().iterator();
                    //卫星颗数统计
                    int count = 0;
                    int countnum = 0;
                    StringBuilder sb = new StringBuilder();
                    String times= KmlUtils.getStringDate();
                    while (iters.hasNext() && count <= maxSatellites) {
                        count++;
                        GpsSatellite s = iters.next();
                        //卫星的信噪比
                        float snr = s.getSnr();
                        if (snr<=STAR_MAX_SNR && snr>=STAR_MIN_SNR && STAR_MAX_SNR > STAR_MIN_SNR) {
                            if (s.getPrn() <= 64 || (s.getPrn() >= 120 && s.getPrn() <= 138)) {
                                dataIntervalBean.add(new DataIntervalBean(s.getPrn(), "GPS", snr,times, countnumber+""));
                            } else if (s.getPrn() >= 201 && s.getPrn() <= 261) {
                                dataIntervalBean.add(new DataIntervalBean(s.getPrn(), "BEIDOU", snr, times,countnumber+""));
                            } else if (s.getPrn() >= 65 && s.getPrn() <= 88) {
                                dataIntervalBean.add(new DataIntervalBean(s.getPrn(), "Glonass", snr,times, countnumber+""));
                            } else if (s.getPrn() >= 301 && s.getPrn() <= 336) {
                                dataIntervalBean.add(new DataIntervalBean(s.getPrn(), "Galileo", snr, times,countnumber+""));
                            }else {
                                dataIntervalBean.add(new DataIntervalBean(s.getPrn(), "", snr, times,countnumber+""));
                            }
                        }else if (STAR_MAX_SNR==STAR_MIN_SNR){
                            if (s.getPrn() <= 64 || (s.getPrn() >= 120 && s.getPrn() <= 138)) {
                                dataIntervalBean.add(new DataIntervalBean(s.getPrn(), "GPS", snr,times, countnumber+""));
                            } else if (s.getPrn() >= 201 && s.getPrn() <= 261) {
                                dataIntervalBean.add(new DataIntervalBean(s.getPrn(), "BEIDOU", snr,times,countnumber+""));
                            } else if (s.getPrn() >= 65 && s.getPrn() <= 88) {
                                dataIntervalBean.add(new DataIntervalBean(s.getPrn(), "Glonass", snr, times,countnumber+""));
                            }else if (s.getPrn() >= 301 && s.getPrn() <= 336) {
                                dataIntervalBean.add(new DataIntervalBean(s.getPrn(), "Galileo", snr, times,countnumber+""));
                            }else {
                                dataIntervalBean.add(new DataIntervalBean(s.getPrn(), "", snr, times,countnumber+""));
                            }
                        }

                    }
                    if(bStar){
                        for (int i=0;i<dataIntervalBean.size();i++){
                            dataIntervalBean1.add(new DataIntervalBean(dataIntervalBean.get(i).getName1(),dataIntervalBean.get(i).getName2(),dataIntervalBean.get(i).getName3(),dataIntervalBean.get(i).getName4(),countnumber+""));
                        }
                        bStar=false;
                        if (countnumber==NUMBER){
                            btnStart.setEnabled(true);
                        }
                    }
                    smartTable.setData(dataIntervalBean1);
                    break;
                default:
                    break;
            }
        }
    };
    private void getExcelInterval(String excelFileName) {
        String filePath = Environment.getExternalStorageDirectory().getPath()+"/GPSTestFile";
        File files = new File(filePath);
        if (!files.exists()) {
            if (files.mkdirs()) {

            } else {
                Toast.makeText(GPSStarInterval.this, "创建失败", Toast.LENGTH_LONG).show();
                return;
            }
        }
        String[] title = {"卫星编码", "卫星类型", "SNR", "日期","次数"};
        String resultPath = files.getAbsolutePath() +"/"+ excelFileName;
        Log.e("rultPath", resultPath);
        ExcelUtil.initExcel(resultPath, title);
        File moudleFile = ExcelUtil.writeObjListToExcel(dataIntervalBean1, resultPath, GPSStarInterval.this, "INTERVAL");
        if (moudleFile != null) {
            Toast.makeText(GPSStarInterval.this, "保存到本地"+resultPath, Toast.LENGTH_LONG).show();
        }
    }

    public void stopGPSListener() {
        if (locationManagerInterval != null) {
            locationManagerInterval.removeUpdates(locationListener);
            locationManagerInterval.removeGpsStatusListener(gpsStatusListener);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopGPSListener();
        handler.removeCallbacks(runnable);
    }
}